package com.googlecode.horncomb.orm.id.generator;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class OracleSequenceIdGenerator extends JdbcDaoSupport implements
		IdGenerator<Long> {
	private String sequenceName = "SEQ_DEFAULT";

	public Long generateId() {
		Long nextId = (Long) this.getJdbcTemplate().execute(
				this.getNextIdSql(), new PreparedStatementCallback() {
					public Object doInPreparedStatement(PreparedStatement stmt)
							throws SQLException, DataAccessException {
						ResultSet rs = stmt.executeQuery();
						rs.next();
						Long id = rs.getLong(1);
						return id;
					}
				});
		return nextId;
	}

	protected String getNextIdSql() {
		return new StringBuilder("SELECT ").append(this.sequenceName).append(
				".NEXTVAL FROM DUAL").toString();
	}

	/**
	 * @param sequenceName
	 *            the sequenceName to set
	 */
	public void setSequenceName(String sequenceName) {
		this.sequenceName = sequenceName;
	}

}
